1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import com.google.common.annotations.GwtCompatible;
20 import com.google.common.collect.MapConstraintsTest.TestKeyException;
21 import com.google.common.collect.MapConstraintsTest.TestValueException;
22 import com.google.common.collect.testing.TestStringMapGenerator;
23
24 import junit.framework.TestCase;
25
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Map.Entry;
29
30
31
32
33
34
35
36 @GwtCompatible(emulated = true)
37 public class ConstrainedMapTest extends TestCase {
38
39 private static final String TEST_KEY = "42";
40 private static final String TEST_VALUE = "test";
41 private static final MapConstraint<String, String> TEST_CONSTRAINT = new TestConstraint();
42
43 public void testPutWithForbiddenKeyForbiddenValue() {
44 Map<String, String> map = MapConstraints.constrainedMap(
45 new HashMap<String, String>(),
46 TEST_CONSTRAINT);
47 try {
48 map.put(TEST_KEY, TEST_VALUE);
49 fail("Expected IllegalArgumentException");
50 } catch (IllegalArgumentException expected) {
51
52 }
53 }
54
55 public void testPutWithForbiddenKeyAllowedValue() {
56 Map<String, String> map = MapConstraints.constrainedMap(
57 new HashMap<String, String>(),
58 TEST_CONSTRAINT);
59 try {
60 map.put(TEST_KEY, "allowed");
61 fail("Expected IllegalArgumentException");
62 } catch (IllegalArgumentException expected) {
63
64 }
65 }
66
67 public void testPutWithAllowedKeyForbiddenValue() {
68 Map<String, String> map = MapConstraints.constrainedMap(
69 new HashMap<String, String>(),
70 TEST_CONSTRAINT);
71 try {
72 map.put("allowed", TEST_VALUE);
73 fail("Expected IllegalArgumentException");
74 } catch (IllegalArgumentException expected) {
75
76 }
77 }
78
79 public static final class ConstrainedMapGenerator extends TestStringMapGenerator {
80 @Override
81 protected Map<String, String> create(Entry<String, String>[] entries) {
82 Map<String, String> map = MapConstraints.constrainedMap(
83 new HashMap<String, String>(),
84 TEST_CONSTRAINT);
85 for (Entry<String, String> entry : entries) {
86 map.put(entry.getKey(), entry.getValue());
87 }
88 return map;
89 }
90 }
91
92 private static final class TestConstraint implements MapConstraint<String, String> {
93 @Override
94 public void checkKeyValue(String key, String value) {
95 if (TEST_KEY.equals(key)) {
96 throw new TestKeyException();
97 }
98 if (TEST_VALUE.equals(value)) {
99 throw new TestValueException();
100 }
101 }
102
103 private static final long serialVersionUID = 0;
104 }
105 }
106